/**
 * Copyright (c) 2015-2016, Michael Yang 杨福海 (fuhai999@gmail.com).
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jpress.admin.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import io.jpress.core.JBaseCRUDController;
import io.jpress.core.interceptor.ActionCacheClearInterceptor;
import io.jpress.model.*;
import io.jpress.model.query.*;
import io.jpress.router.RouterMapping;
import io.jpress.router.RouterNotAllowConvert;
import io.jpress.utils.DateUtils;
import io.jpress.utils.HttpUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RouterMapping(url = "/data", viewPath = "/WEB-INF/admin/data")
@Before(ActionCacheClearInterceptor.class)
@RouterNotAllowConvert
public class _DataShowController extends JBaseCRUDController<HouseData> {

	public void bigIndex() {
		makeData();

	}

	public void makeData(){
		setAttr("hallMap",HallEnum.getHallMap());

		/**折线图*/
		List<HouseData> day1 = HouseDataQuery.me().findList(1,Integer.MAX_VALUE,"day1","time");
		List<HouseData> day2 = HouseDataQuery.me().findList(1,Integer.MAX_VALUE,"day2","time");
		List<HouseData> day3 = HouseDataQuery.me().findList(1,Integer.MAX_VALUE,"day3","time");

		Map<String,Object> lineData = new HashMap<>();

		lineData.put("D1",buildMap(day1));
		lineData.put("D2",buildMap(day2));
		lineData.put("D3",buildMap(day3));

		setAttr("lineData", JSONObject.toJSONString(lineData));

		/**柱状图*/
		List<String> categories = new ArrayList<>();
		List<Integer> need = new ArrayList<>();
		List<Integer> order = new ArrayList<>();
		List<Integer> trade = new ArrayList<>();

		int needNum = 0;
		int orderNum = 0;
		int tradeNum = 0;

		List<NotData> list = NotDataQuery.me().findList();
		for (NotData data : list){
			if(data.getHall().equals("5")){
				needNum = data.getNeedNum();
				orderNum = data.getOrderNum();
				tradeNum = data.getTradeNum();
				continue;
			}
			categories.add(HallEnum.getValue(Integer.parseInt(data.getHall())));
			need.add(data.getNeedNum());
			order.add(data.getOrderNum());
			trade.add(data.getTradeNum());
		}

		Collections.sort(list, new Comparator<NotData>() {
			@Override
			public int compare(NotData o1, NotData o2) {
				return -o1.getTradeNum()-o2.getTradeNum();
			}
		});
		setAttr("tradeList",list);

		Map<String,Object> bar1 = new HashMap<>();
		bar1.put("categories",categories);
		bar1.put("neednum",need);
		bar1.put("ordernum",order);
		bar1.put("tradenum",trade);
		setAttr("bar1",JSONObject.toJSONString(bar1));

		Map<String,Object> bar2 = new HashMap<>();
		bar2.put("categories",new String[]{"A B C"});
		bar2.put("neednum",new Integer[]{needNum});
		bar2.put("ordernum",new Integer[]{orderNum});
		bar2.put("tradenum",new Integer[]{tradeNum});
		setAttr("bar2",JSONObject.toJSONString(bar2));

		/**其他数据*/
		Summary summary = new Summary().findById("1");
		setAttr("summary",summary);

		setAttr("tradenum",summary.getLeftNum());
		setAttr("tradeaccount",summary.getRightNum());

		/**供应信息数/需求信息数*/
		Map<String,String> num = new HashMap<>();
		num.put("total","1万");
		num.put("supply",summary.getProvideNum().toString());
		num.put("need",summary.getNeedNum().toString());
		setAttr("num",JSONObject.toJSONString(num));

		/**新闻列表数据*/
		List<Msg> msgList = MsgQuery.me().findList();
		Map<String,List<Msg>> message = buildMsgMap(msgList);
		setAttr("message",JSONObject.toJSONString(message));

	}

	public Map<String,Object> buildMap (List<HouseData> list){
		Map<String, Object> option = new HashMap();

		List<Integer> list0 = new ArrayList<>();
		List<Integer> list1 = new ArrayList<>();
		List<Integer> list2 = new ArrayList<>();
		List<Integer> list3 = new ArrayList<>();
		List<Integer> list4 = new ArrayList<>();
		List<String> list5 = new ArrayList<>();

		for(HouseData data:list){
			list0.add(data.getHall0());
			list1.add(data.getHall1());
			list2.add(data.getHall2());
			list3.add(data.getHall3());
			list4.add(data.getHall4());
			list5.add(DateUtils.format(data.getTime(),DateUtils.timeSdf));
		}

		option.put("report",list0);
		option.put("business",list1);
		option.put("life",list2);
		option.put("comprehensive",list3);
		option.put("intelligent",list4);
		option.put("categories",list5);

		return option;
	}

	public void miniIndex(){
		makeData();
	}

	public void refreshData(){
		Map<String,Object> json = new HashMap<>();
		json.put("hallMap",HallEnum.getHallMap());

		/**折线图*/
		List<HouseData> day1 = HouseDataQuery.me().findList(1,Integer.MAX_VALUE,"day1","time");
		List<HouseData> day2 = HouseDataQuery.me().findList(1,Integer.MAX_VALUE,"day2","time");
		List<HouseData> day3 = HouseDataQuery.me().findList(1,Integer.MAX_VALUE,"day3","time");

		Map<String,Object> lineData = new HashMap<>();

		lineData.put("D1",buildMap(day1));
		lineData.put("D2",buildMap(day2));
		lineData.put("D3",buildMap(day3));

		json.put("lineData", JSONObject.toJSONString(lineData));

		/**柱状图*/
		List<String> categories = new ArrayList<>();
		List<Integer> need = new ArrayList<>();
		List<Integer> order = new ArrayList<>();
		List<Integer> trade = new ArrayList<>();

		int needNum = 0;
		int orderNum = 0;
		int tradeNum = 0;

		List<NotData> list = NotDataQuery.me().findList();
		for (NotData data : list){
			if(data.getHall().equals("5")){
				needNum = data.getNeedNum();
				orderNum = data.getOrderNum();
				tradeNum = data.getTradeNum();
				continue;
			}
			categories.add(HallEnum.getValue(Integer.parseInt(data.getHall())));
			need.add(data.getNeedNum());
			order.add(data.getOrderNum());
			trade.add(data.getTradeNum());
		}

		Collections.sort(list, new Comparator<NotData>() {
			@Override
			public int compare(NotData o1, NotData o2) {
				return -o1.getTradeNum()-o2.getTradeNum();
			}
		});
		json.put("tradeList",list);

		Map<String,Object> bar1 = new HashMap<>();
		bar1.put("categories",categories);
		bar1.put("neednum",need);
		bar1.put("ordernum",order);
		bar1.put("tradenum",trade);
		json.put("bar1",JSONObject.toJSONString(bar1));

		Map<String,Object> bar2 = new HashMap<>();
		bar2.put("categories",new String[]{"A B C"});
		bar2.put("neednum",new Integer[]{needNum});
		bar2.put("ordernum",new Integer[]{orderNum});
		bar2.put("tradenum",new Integer[]{tradeNum});
		json.put("bar2",JSONObject.toJSONString(bar2));

		/**其他数据*/
		Summary summary = new Summary().findById("1");
		json.put("summary",summary);

		setAttr("tradenum",summary.getLeftNum());
		setAttr("tradeaccount",summary.getRightNum());

		/**供应信息数/需求信息数*/
		Map<String,String> num = new HashMap<>();
		num.put("total","1万");
		num.put("supply",summary.getProvideNum().toString());
		num.put("need",summary.getNeedNum().toString());
		json.put("num",JSONObject.toJSONString(num));

		/**新闻列表数据*/
		List<Msg> msgList = MsgQuery.me().findList();
		Map<String,List<Msg>> message = buildMsgMap(msgList);

		json.put("message",JSONObject.toJSONStringWithDateFormat(message,"HHmmss"));

		renderAjaxResultForSuccess("ok",JSONObject.toJSONString(json));
	}

	public Map<String,List<Msg>> buildMsgMap(List<Msg> msgList){
		List<Msg> supply = new ArrayList<>();
		List<Msg> channel = new ArrayList<>();
		List<Msg> news = new ArrayList<>();
		for (Msg msg : msgList){
			if(msg.getType().equals(MsgTypeEnum.ZHENGCE.getKey())){
				supply.add(msg);
			}else if (msg.getType().equals(MsgTypeEnum.YAOWEN.getKey())){
				channel.add(msg);
			}else if (msg.getType().equals(MsgTypeEnum.DONGTAI.getKey())){
				news.add(msg);
			}
		}
		Map<String,List<Msg>> message = new HashMap<>();
		Collections.sort(supply, new Comparator<Msg>() {
			@Override
			public int compare(Msg o1, Msg o2) {
				return o1.getTime().getTime() - o2.getTime().getTime()>0?-1:1;
			}
		});
		Collections.sort(channel, new Comparator<Msg>() {
			@Override
			public int compare(Msg o1, Msg o2) {
				return o1.getTime().getTime() - o2.getTime().getTime()>0?-1:1;
			}
		});
		Collections.sort(news, new Comparator<Msg>() {
			@Override
			public int compare(Msg o1, Msg o2) {
				return o1.getTime().getTime() - o2.getTime().getTime()>0?-1:1;
			}
		});
		message.put("supply",supply);
		message.put("channel",channel);
		message.put("news",news);
		return  message;
	}

	public void dataIndex(){
	}

	public SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

	public void refreshDataTj(){
		Map<String,Object> map = new HashMap<>();
		Map<String,Object> scMap = new HashMap<>();

		List<TjSsj> tjSsjList = TjSsjQuery.me().findList(1,Integer.MAX_VALUE,"day");

		List<String> dayList = new ArrayList<>();
		List<Integer> scList = new ArrayList<>();
		List<Integer> stsList = new ArrayList<>();
		List<Integer> jyList = new ArrayList<>();

		for (TjSsj ssj : tjSsjList){
			dayList.add(sdf.format(ssj.getDay()));
			scList.add(ssj.getShuangChuang());
			stsList.add(ssj.getShengTaiShu());
			jyList.add(ssj.getJiuYe());
		}
		scMap.put("dayList", dayList);
		scMap.put("scList", scList);
		scMap.put("stsList", stsList);
		scMap.put("jyList", jyList);
		map.put("scMap",scMap);

		Map<String,Object> kjcgMap = new HashMap<>();
		List<TjKjcg> kjcgList = TjKjcgQuery.me().findList();
		List<String> yearList = new ArrayList<>();
		List<Integer> yjyxList = new ArrayList<>();
		List<Integer> lmggList = new ArrayList<>();
		List<Integer> spggList = new ArrayList<>();
		for (TjKjcg kjcg:kjcgList){
			yearList.add(kjcg.getYear());
			yjyxList.add(kjcg.getYjyx());
			lmggList.add(kjcg.getLmgg());
			spggList.add(kjcg.getSpgg());
		}
		kjcgMap.put("year",yearList);
		kjcgMap.put("yjyx",yjyxList);
		kjcgMap.put("lmgg",lmggList);
		kjcgMap.put("spgg",spggList);

		map.put("kjcg",kjcgMap);

		Map<String,Object> dzcyMap = new HashMap<>();
		List<TjDzcy> dzcyList = TjDzcyQuery.me().findList();
		List<String> month = new ArrayList<>();
		List<Integer> a = new ArrayList<>();
		List<Integer> b = new ArrayList<>();
		List<Integer> c = new ArrayList<>();
		for (TjDzcy dzcy:dzcyList){
			month.add(dzcy.getMonth());
			a.add(dzcy.getA());
			b.add(dzcy.getB());
			c.add(dzcy.getC());
		}
		dzcyMap.put("month",month);
		dzcyMap.put("a",a);
		dzcyMap.put("b",b);
		dzcyMap.put("c",c);
		map.put("dzcy",dzcyMap);

		Map<String,Object> summaryMap = new HashMap<>();
		TjSummary tjSummary = new TjSummary().findById(1);
		summaryMap.put("trade_num",tjSummary.getTradeNum().split("/"));

		JSONArray zhuanli = new JSONArray();
		List<Map<String,Object>> zhuanliList = new ArrayList<>();
		String[] zlNum = tjSummary.getZhuanLi().split("/");
		JSONObject json = new JSONObject();
		json.put("value",Integer.valueOf(zlNum[0]));
		json.put("name","发明");
		zhuanli.add(json);
		JSONObject json1 = new JSONObject();
		json1.put("value",Integer.valueOf(zlNum[1]));
		json1.put("name","实用新型");
		zhuanli.add(json1);
		JSONObject json2 = new JSONObject();
		json2.put("value",Integer.valueOf(zlNum[2]));
		json2.put("name","外观设计");
		zhuanli.add(json2);
		JSONObject json3 = new JSONObject();
		json3.put("value",Integer.valueOf(zlNum[0])+Integer.valueOf(zlNum[1])+Integer.valueOf(zlNum[2]));
		json3.put("name","合计");
		zhuanli.add(json3);
		summaryMap.put("zhuanli",zhuanli);

		JSONArray shangshi = new JSONArray();
		String[] ssNum = tjSummary.getShangShi().split("/");
		JSONObject json4 = new JSONObject();
		json4.put("value",Integer.valueOf(ssNum[0]));
		json4.put("name","已上市");
		shangshi.add(json4);
		JSONObject json5 = new JSONObject();
		json5.put("value",Integer.valueOf(ssNum[1]));
		json5.put("name","战略投资");
		shangshi.add(json5);
		JSONObject json6 = new JSONObject();
		json6.put("value",Integer.valueOf(ssNum[2]));
		json6.put("name","第三板");
		shangshi.add(json6);
		summaryMap.put("shangshi",shangshi);

		Map<String,Object> scqyMap = new HashMap<>();
		scqyMap.put("cygs",tjSummary.getScQy().split("/")[0]);
		scqyMap.put("tzjg",tjSummary.getScQy().split("/")[1]);
		scqyMap.put("sczt",tjSummary.getScQy().split("/")[2]);
		scqyMap.put("sum",Integer.valueOf(tjSummary.getScQy().split("/")[0])+Integer.valueOf(tjSummary.getScQy().split("/")[1])+Integer.valueOf(tjSummary.getScQy().split("/")[2]));
		summaryMap.put("scqy",scqyMap);
		summaryMap.put("rightNum",tjSummary.getRightNum());

		map.put("summary",summaryMap);

		/**新闻列表数据*/
		List<Msg> msgList = MsgQuery.me().findList();
		Map<String,List<Msg>> message = buildMsgMap(msgList);

		map.put("message",JSONObject.toJSONStringWithDateFormat(message,"HHmmss"));

		List<TjYjxmcg> yjxmcgList = TjYjxmcgQuery.me().findList();
		List<Map<String,Object>> yjxmcg = new ArrayList<>();
		for (TjYjxmcg xmcg:yjxmcgList){
			Map<String,Object> xmcgMap = new HashMap<>();
			xmcgMap.put("name",xmcg.getName());
			List<Integer> value = new ArrayList<>();
			value.add(xmcg.getValue1());
			value.add(xmcg.getValue2());
			value.add(xmcg.getValue3());
			value.add(xmcg.getValue4());
			xmcgMap.put("list",value);
			yjxmcg.add(xmcgMap);
		}
		map.put("yjxmcg",yjxmcg);

		map.put("weather",getweather());


		renderAjaxResultForSuccess("ok", JSONObject.toJSONString(map));

	}

	public static Map<String,String> getweather() {
		Map<String,String> map = new HashMap<>();

		try {

			String xml = HttpUtils.get("http://php.weather.sina.com.cn/xml.php?city=" + URLEncoder.encode("天津", "gb2312") + "&password=DJOYnieT8234jlsK&day=0",null);
			Document document = Jsoup.parse(xml);
			Elements ele = document.select("weather");
			map.put("city",ele.select("city").text());
			map.put("status1",ele.select("status1").text());
			map.put("direction2",ele.select("direction2").text());
			map.put("power2",ele.select("power2").text());
			map.put("temperature1",ele.select("temperature1").text());
			map.put("figure1",ele.select("figure1").text());

		}catch (Exception e){

		}
		return map;
	}

	public static void main(String[] args){
		System.out.println(JSON.toJSONString(getweather()));
	}


}
